package handerls

import (
	"admin-pro/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.NodeRole{
		Rid: rid,
		Nid: nid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{

		Uid: uid,
		Rid: rid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

// 用户与角色关联
func UserRole(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT*FROM
		roles
		left JOIN user_roles ON user_roles.uid=roles.id
		WHERE user_roles.uid=1*/

	var arr []models.Role
	models.DB.Table("roles").Joins("left JOIN user_roles ON user_roles.uid=roles.id").
		Where("user_roles.uid=?", uid).
		Find(&arr)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
	return
}

// 角色与权限关联
func NodeRole(c *gin.Context) {
	rid := c.Query("rid")
	/*
			SELECT*FROM
		nodes
		left JOIN node_roles ON node_roles.rid=nodes.id
		WHERE node_roles.rid=1*/

	var arr []models.Node
	models.DB.Table("nodes").Joins("left JOIN node_roles ON node_roles.rid=nodes.id").
		Where("node_roles.rid=?", rid).
		Find(&arr)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
	return
}
